home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cpptutor.arc / CHAP01.TXT < prev    next >
Text File  |  1991-04-28  |  23KB  |  531 lines

  1.  
  2.  
  3.  
  4.                                                           Chapter 1
  5.                                                       SIMPLE THINGS
  6.  
  7. As we begin the study of C++ and object oriented programming, a few
  8. comments are in order to help you get started.  Since the field of
  9. object oriented programming is probably new to you, you will find
  10. that there is a significant amount of new terminology for you to
  11. grasp.  This is true of any new endeavor and you should be warned
  12. not to be intimidated by all of the new concepts.  We will add a
  13. few new topics in each chapter and you will slowly grasp the entire
  14. language.
  15.  
  16. Chapters one through four of this tutorial will concentrate on the
  17. non object oriented programming additions to C++.  We will not
  18. begin the discussion of any object oriented programming techniques
  19. until chapter five.
  20.  
  21.  
  22. EVEN COMMENTS ARE IMPROVED IN C++
  23. _________________________________________________________________
  24.  
  25. Examine the file named CONCOM.CPP for an example   ==============
  26. of several new things in C++.  We will take the      CONCOM.CPP
  27. new constructs one at a time beginning with the    ==============
  28. comments.
  29.  
  30. A comment begins with the double slash "//", starts anywhere on a
  31. line and runs to the end of that line where it is automatically
  32. terminated.  The old method of comment definition used with ANSI-
  33. C can also be used with C++ as illustrated in lines 11 through 14,
  34. among other places in this program.  The new method is the
  35. preferred method of comment definition because it is impossible to
  36. inadvertently comment out several lines of code.  This can be done
  37. by forgetting to include the end of comment notation when using the
  38. older C method of comment notation.  Good programming practice
  39. would be to use the new method for all comments and reserve the old
  40. method for use in commenting out a section of code during debugging
  41. since the two methods can be nested.
  42.  
  43. It would be well to caution you at his point however, that you
  44. should not use comments when the same sense of program definition
  45. can be obtained by using meaningful names for variables, constants,
  46. and functions.  The careful selection of variable and function
  47. names can make nearly any code self documenting and you should
  48. strive to achieve this in your code.
  49.  
  50. THE KEYWORDS const AND volatile
  51. _________________________________________________________________
  52.  
  53. There are two new keywords used in lines 9 through 11 which were
  54. not part of the original K&R definition of C, but are part of the
  55. ANSI-C standard.  The keyword const is used to define a constant. 
  56. In line 9 the constant is of type int, it is named START, and is
  57.  
  58.                                                            Page 1-1
  59.  
  60.                                           Chapter 1 - Simple Things
  61.  
  62. initialized to the value 3.  The compiler will not allow you to
  63. accidentally or purposefully change the value of START because it
  64. has been declared a constant.  If you had another variable named
  65. STARTS, the system would not allow you to slightly misspell STARTS
  66. as START and accidentally change it.  The compiler would give you
  67. an error message so you could fix the error.  Since it is not
  68. permissible to change the value of a constant, it is imperative
  69. that you initialize it when it is declared so it will have a useful
  70. value.  The compiler does not require you to initialize it however,
  71. and will not issue an error message if you do not.
  72.  
  73. You will note that the keyword const is also used in the function
  74. header in line 21 to indicate that the formal parameter named
  75. data_value is a constant throughout the function.  Any attempt to
  76. assign a new value to this variable will result in a compile error. 
  77. This is a small thing you can add to your programs to improve the
  78. compilers ability to detect errors for you.
  79.  
  80. The keyword volatile is also part of the ANSI-C standard but was
  81. not included in the original K&R definition of C.  Even though the
  82. value of a volatile variable can be changed by you, the programmer,
  83. there may be another mechanism by which the value could be changed,
  84. such as by an interrupt timer causing the value to be incremented. 
  85. The compiler needs to know that this value may be changed by some
  86. external force when it optimizes the code.  A study of code
  87. optimization methods is very interesting, but beyond the scope of
  88. this tutorial.  Note that a constant can also be volatile, which
  89. means that you cannot change it, but the system can through some
  90. hardware function.
  91.  
  92. Ignore the output statement given in line 23 for a few minutes. 
  93. We will study it in some detail later in this chapter.  If you are
  94. experienced in K&R style programming, you may find line 5 and 21
  95. a little strange.  This illustrates prototyping and the modern
  96. method of function definition as defined by the ANSI-C standard. 
  97. We will discuss this in great detail in chapter 4 of this tutorial. 
  98. Prototyping is optional in C but absolutely required in C++.  For
  99. that reason, chapter 4 of this tutorial is devoted entirely to this
  100. topic.
  101.  
  102. It would be advantageous for you to compile and execute this
  103. program with your C++ compiler to see if you get the same result
  104. as given in the comments at the end of the listing.  One of the
  105. primary purposes of compiling it is to prove that your compiler is
  106. loaded and executing properly.
  107.  
  108.  
  109.  
  110. THE SCOPE OPERATOR
  111. _________________________________________________________________
  112.  
  113. The example program named SCOPEOP.CPP illustrates another construct
  114. that is new to C++.  There is no corresponding construct in either
  115. K&R or ANSI-C.  This allows access to the global variable named
  116.  
  117.                                                            Page 1-2
  118.  
  119.                                           Chapter 1 - Simple Things
  120.  
  121. index even though there is a local variable of      ===============
  122. the same name within the main function.  The use      SCOPEOP.CPP
  123. of the double colon in front of the variable        ===============
  124. name, in lines 11, 13, and 16, instructs the
  125. system that we are interested in using the
  126. global variable named index, defined in line 4, rather than the
  127. local variable defined in line 8.
  128.  
  129. The use of this technique allows access to the global variable for
  130. any use.  It could be used in calculations, as a function
  131. parameter, or for any other purpose.  It is not really good
  132. programming practice to abuse this construct, because it could make
  133. the code difficult to read.  It would be best to use a different
  134. variable name instead of reusing this name, but the construct is
  135. available to you if you find that you need it sometime.
  136.  
  137. The scope operator allows access to global variables even though
  138. hidden by a local variable.  Be sure to compile and execute this
  139. program before proceeding on to the next example program where we
  140. will discuss the cout operator in lines 10, 11, 15, and 16.
  141.  
  142.  
  143.  
  144. THE iostream LIBRARY
  145. _________________________________________________________________
  146.  
  147. Examine the example program named MESSAGE.CPP     ===============
  148. for our first hint of object oriented               MESSAGE.CPP
  149. programming, even though it is a very simple      ===============
  150. one.  In this program, we define a few variables
  151. and assign values to them for use in the output
  152. statements illustrated in lines 17 through 20, and in lines 23
  153. through 26.  The new operator cout is the output function to the
  154. standard device, the monitor, but works a little differently from
  155. our old familiar printf() function, because we do not have to tell
  156. the system what type we are outputting.
  157.  
  158. C++, like the C language itself, has no input or output operations
  159. as part of the language itself, but allows the implementor to add
  160. input and output functions in a very elegant manner.  This has been
  161. done for us in the stream library.
  162.  
  163. The operator <<, sometimes called the "put to" operator, tells the
  164. system to output the variable or constant following it, but lets
  165. the system decide how to output the data.  In line 17, we first
  166. tell the system to output the string, which it does by copying
  167. characters to the monitor, then we tell it to output the value of
  168. index.  Notice however, that we fail to tell it what the type is
  169. or how to output the value.  Since we don't tell the system what
  170. the type is, it is up to the system to determine what the type is
  171. and to output the value accordingly.  After the system finds the
  172. correct type, we also leave it up to the system to use the built
  173. in default as to how many characters should be used for this
  174. output.  In this case, we find that the system uses exactly as many
  175.  
  176.                                                            Page 1-3
  177.  
  178.                                           Chapter 1 - Simple Things
  179.  
  180. as needed to output the data, with no leading or trailing blanks,
  181. which is fine for this output.  Finally, the newline character is
  182. output, and the line of code is terminated with a semicolon.
  183.  
  184. When we called the cout output function in line 17, we actually
  185. called two different functions because we used it to output a
  186. string and a variable of type int.  This is the first hint at
  187. object oriented programming because we simply broadcast a message
  188. to the system to print out a value, and let the system find an
  189. appropriate function to do so.  We are not required to tell the
  190. system exactly how to output the data, we only tell it to output
  191. it.  This is a very weak example of object oriented programming,
  192. and we will get into it in much more depth later.
  193.  
  194. In line 18, we tell the system to output a different string,
  195. followed by a floating point number, and another string of one
  196. character, the newline character.  In this case, we told it to
  197. output a floating point number without telling it that it was a
  198. floating point number, once again letting the system choose the
  199. appropriate output means based on its type.  We did lose a bit of
  200. control in the transaction, however, because we had no control over
  201. how many significant digits to print before or after the decimal
  202. point.  We chose to let the system decide how to format the output
  203. data.
  204.  
  205.  
  206. The variable named letter is of type char, and is assigned the
  207. value of the uppercase X in line 14, then printed as a letter in
  208. line 19.  You have complete flexibility in the use of the cout and
  209. the printf() statements and they can be mixed in any way you
  210. desire.  Both statements result in output to the monitor.
  211.  
  212.  
  213. MORE ABOUT THE stream LIBRARY
  214. _________________________________________________________________
  215.  
  216. The stream library was defined for use with C++ in order to add to
  217. the execution efficiency of the language.  The printf() function
  218. was developed early in the life of the C language and is meant to
  219. be all things to all programmers.  As a result, it became a huge
  220. function with lots of extra baggage that is only used by a few
  221. programmers.  By defining the small special purpose stream library,
  222. the designer of C++ allows the programmer to use somewhat limited
  223. formatting capabilities, but which are still adequate for most
  224. programming jobs.  If more elaborate formatting capabilities are
  225. required, the complete printf() library is available from C, and
  226. the two types of outputs can be freely mixed.
  227.  
  228. Lines 23 through 26 illustrate some of the additional features of
  229. the stream library which can be used to output data in a very
  230. flexible yet controlled format.  The value of index is printed out
  231. in decimal, octal, and hexadecimal format in lines 23 through 25. 
  232. When one of the special stream operators, dec, oct, or hex, is
  233. output, all successive output will be in that number base.  Looking
  234.  
  235.                                                            Page 1-4
  236.  
  237.                                           Chapter 1 - Simple Things
  238.  
  239. ahead to line 32, we find the value of index printed in hex format
  240. due to the selection of the hexadecimal base in line 25.  If none
  241. of these are output, the system defaults to decimal format.
  242.  
  243.  
  244. THE cin OPERATOR
  245. _________________________________________________________________
  246.  
  247. In addition to the cout operator, there is a cin operator which is
  248. used to read data from the standard input device, usually the
  249. keyboard.  The cin operator uses the >> operator, usually called
  250. the "get from" operator and it has most of the flexibility of the
  251. cout operator.  A brief example of the use of the cin operator is
  252. given in lines 28 through 30.  The special stream operators, dec,
  253. oct, and hex, also select the number base for the cin stream
  254. separately from the cout stream.  If none is specified, the input
  255. stream also defaults to decimal.
  256.  
  257. In addition to the cout operator and the cin operator there is one
  258. more standard operator, the cerr, which is used to output to the
  259. error handling device.  This device cannot be redirected to a file
  260. like the output to the cout can be.  The three operators, cout,
  261. cin, and cerr, correspond roughly to the stdout, the stdin, and the
  262. stderr stream pointers of the programming language C.  Their use
  263. will be illustrated throughout the remainder of this tutorial.
  264.  
  265. The stream library also has file I/O capability, but it is beyond
  266. the scope of this tutorial.  The standard file I/O library is
  267. available with ANSI-C and is as easy to use as the stream library
  268. and very portable.  For more information on the stream file I/O
  269. library, see Bjarne Stroustrup's book which is listed in the
  270. introduction to this tutorial.
  271.  
  272. Be sure to compile and execute this program before going on to the
  273. next one.  Remember that the system will ask you to enter an
  274. integer value which will be echoed back to the monitor, but changed
  275. to the hexadecimal base.
  276.  
  277.  
  278.  
  279. FILE STREAM OPERATIONS
  280. _________________________________________________________________
  281.  
  282. Examine the example program named FSTREAM.CPP     ===============
  283. for examples of the use of streams with files.      FSTREAM.CPP
  284. In this program a file is opened for reading,     ===============
  285. another for writing, and a third stream is
  286. opened to the printer to illustrate the semantics of stream
  287. operations on a file.  The only difference between the streams in
  288. the last program and the streams in this program is the fact that
  289. in the last program, the streams were already opened for us by the
  290. system.  You will note that the stream named printer is used in the
  291. same way we used the cout operator in the last program.  Finally,
  292.  
  293.                                                            Page 1-5
  294.  
  295.                                           Chapter 1 - Simple Things
  296.  
  297. because we wish to exercise good programming practice, we close
  298. all of the files we have opened prior to ending the program.
  299.  
  300. Be sure to compile and execute this program.  When you execute it,
  301. it will request a file to be copied.  You can enter the name of any
  302. ASCII file that resides in the current directory.
  303.  
  304.  
  305.  
  306. VARIABLE DEFINITIONS
  307. _________________________________________________________________
  308.  
  309. Examine the file named VARDEF.CPP for a few more   ==============
  310. additions to the C++ language which aid in           VARDEF.CPP
  311. writing a clear and easy to understand program.    ==============
  312. In C++, as in ANSI-C, global and static
  313. variables are automatically initialized to zero
  314. when they are declared.  This is true in both C++ and ANSI-C.  The
  315. variables named index in line 4, and goofy in line 26 are therefore
  316. automatically initialized to zero.  Of course, you can still
  317. initialize either to some other value if you so desire.  Global
  318. variables are sometimes called external since they are external to
  319. any functions.
  320.  
  321. Automatic variables, those declared inside of any function, are not
  322. automatically initialized but will contain the value that happens
  323. to be in the location where they are defined, which must be
  324. considered a garbage value.  The variable named stuff in line 8,
  325. therefore does not contain a valid value, but some garbage value
  326. which should not be used for any meaningful purpose.  In line 11,
  327. it is assigned a value based on the initialized value of index and
  328. it is then displayed on the monitor for your examination.
  329.  
  330.  
  331.  
  332. THE REFERENCE VARIABLE
  333. _________________________________________________________________
  334.  
  335. Notice the ampersand in line 9.  This defines another_stuff as a
  336. reference variable which is a new addition to C++.  The reference
  337. variable should not be used very often, if at all, in this context. 
  338. In order to be complete however, we will discuss its operation. 
  339. The reference variable is not quite the same as any other variable
  340. because it operates sort of like a pointer.  Following its
  341. initialization, the reference variable becomes a synonym for the
  342. variable stuff, and changing the value of stuff will change the
  343. value of another_stuff because they are both actually referring to
  344. the same variable.  The synonym can be used to access the value of
  345. the variable for any legal purpose in the language.  It should be
  346. pointed out that a reference variable must be initialized when it
  347. is declared or the compiler will respond with an error.  Following
  348. initialization, the reference variable cannot be changed to refer
  349. to a different variable.
  350.  
  351.  
  352.                                                            Page 1-6
  353.  
  354.                                           Chapter 1 - Simple Things
  355.  
  356. Even though the use of the reference variable in this way can lead
  357. to very confusing code, it has another use where it can make the
  358. code very clear and easy to understand.  We will study this use in
  359. chapter 4 of this tutorial. 
  360.  
  361.  
  362. DEFINITIONS ARE EXECUTABLE STATEMENTS
  363. _________________________________________________________________
  364.  
  365. Coming from your background of C, you will find the statement in
  366. line 16 very strange, but this is legal in C++.  Anyplace it is
  367. legal to put an executable statement, it is also legal to declare
  368. a new variable because a data declaration is defined as an
  369. executable statement in C++.  In this case, we define the new
  370. variable named more_stuff and initialize it to the value of 13. 
  371. It has a scope from the point where it was defined to the end of
  372. the block in which it is defined, so it is valid throughout the
  373. remainder of the main program.  The variable named goofy is
  374. declared even later in line 26.
  375.  
  376. It is very significant that the variable is declared near its point
  377. of usage.  This makes it easier to see just what the variable is
  378. used for since it has a much more restricted scope of validity. 
  379. When you are debugging a program, it is convenient if the variable
  380. declaration is located in close proximity to where you are
  381. debugging the code.
  382.  
  383.  
  384.  
  385. WHAT ABOUT definition AND declaration?
  386. _________________________________________________________________
  387.  
  388. The words definition and declaration refer to two different things
  389. in C++, and in ANSI-C also for that matter.  They really are
  390. different and have different characteristics so we should spend a
  391. little time defining exactly what the words mean in C++.  A
  392. declaration provides information to the compiler about the
  393. characteristics of something such as a type or a function but it
  394. doesn't actually define any code to be used in the executable
  395. program, and you are permitted to make as many declarations of the
  396. same entity as you desire.  A definition, on the other hand,
  397. actually defines something that will exist in the executable
  398. program, either some useful variables, or some executable code, and
  399. you are required to have one and only one definition of each entity
  400. in the program.  In short, a declaration introduces a name into the
  401. program and a definition introduces some code.
  402.  
  403. If we declare a struct, we are only declaring a pattern to tell the
  404. compiler how to store data later when we define one or more
  405. variables of that type.  But when we define some variables of that
  406. type, we are actually declaring their names for use by the
  407. compiler, and defining a storage location to store the values of
  408. the variables.  Therefore, when we define a variable, we are
  409. actually declaring it and defining it at the same time.
  410.  
  411.                                                            Page 1-7
  412.  
  413.                                           Chapter 1 - Simple Things
  414.  
  415.  
  416. We will refer to these definitions many times throughout the course
  417. of this tutorial so if this is not clear now, it will clear up
  418. later.
  419.  
  420.  
  421. A BETTER for LOOP
  422. _________________________________________________________________
  423.  
  424. Take careful notice of the for loop defined in line 20.  This loop
  425. is a little clearer than the for loop that is available in ANSI-C,
  426. because the loop index is defined in the for loop itself.  The
  427. scope of this loop index is from its declaration to the end of the
  428. enclosing block.  In this case its scope extends to line 29 since
  429. the closing brace in line 29 corresponds to the most recent opening
  430. brace prior to the declaration of the variable.  Since the variable
  431. is still available, it can be used for another loop index or for
  432. any other purpose which an integer type variable can legally be
  433. used for.  The variable named count2 is declared and initialized
  434. during each pass through the loop because it is declared within the
  435. block controlled by the for loop.  Its scope is only the extent of
  436. the loop so that it is automatically deallocated each time the loop
  437. is completed.  It is therefore declared, initialized, used and
  438. deallocated five times, once for each pass through the loop.
  439.  
  440. You will notice that the variable count2 is assigned a numerical
  441. value in line 22 but when it is printed out, a character value is
  442. actually output.  This is because C++ (version 2.0 and later) is
  443. careful to use the correct type.
  444.  
  445. Finally, as mentioned earlier, the static variable named goofy is
  446. declared and automatically initialized to zero in line 26.  Its
  447. scope is from the point of its declaration to the end of the block
  448. in which it is declared, line 29.
  449.  
  450. Be sure to compile and execute this program.
  451.  
  452.  
  453.  
  454. OPERATOR PRECEDENCE
  455. _________________________________________________________________
  456.  
  457. Operator precedence is identical to that defined for ANSI-C so no
  458. attempt will be made here to define it.  There is a small
  459. difference when some operators are overloaded which we will learn
  460. to do later in this tutorial.  Some of the operators act slightly
  461. different when overloaded than the way they operate with elements
  462. of the predefined language.
  463.  
  464. Do not worry about the previous paragraph, it will make sense later
  465. in this tutorial after we have studied a few more topics.
  466.  
  467.  
  468.  
  469.  
  470.                                                            Page 1-8
  471.  
  472.                                           Chapter 1 - Simple Things
  473.  
  474. PROGRAMMING EXERCISES
  475. _________________________________________________________________
  476.  
  477.  
  478. 1.   Write a program that displays your name and date of birth on
  479.      the monitor three times using the cout function.  Define any
  480.      variables you use as near as possible to their point of usage.
  481.  
  482. 2.   Write a program with a few const values and volatile variables
  483.      and attempt to change the value of the constants to see what
  484.      kind of error message your compiler will give you.
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.                                                            Page 1-9
  530.  
  531.